<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        ref="form"
        :model="form.val"
        :rules="form.rules"
        :label-col="form.labelCol"
        :wrapper-col="form.wrapperCol"
      >
        <a-form-model-item label="名称" prop="name">
          <a-input v-model="form.val.name" placeholder="请输入" />
        </a-form-model-item>
        <a-form-item label="描述" prop="des">
          <a-textarea
            autoSize
            placeholder="请输入，不超过200字"
            :max-length="200"
            v-model="form.val.des"
          />
        </a-form-item>
      </a-form-model>
    </a-spin>
    <a-form-item class="form-btn">
      <a-button @click="closeDetail(false)">取消</a-button>
      <a-button type="primary" :loading="form.confirmLoading" @click="onSubmit('form')">确定</a-button>
    </a-form-item>
  </div>
</template>

<script>
import { getGroupInfo, createGroupInfo, updateGroupInfo } from '@/api/system'

export default {
  props: {
    currentInfo: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      spinning: false,
      form: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 21 }
        },
        confirmLoading: false,
        val: {},
        rules: {
          name: [{ required: true, message: '名称不可为空', trigger: 'blur' }]
        }
      }
    }
  },
  watch: {
    'currentInfo.id': {
      handler: 'resetForm',
      immediate: true
    }
  },
  methods: {
    // 重构表单内容
    resetForm (val) {
      this.form.confirmLoading = false
      this.$nextTick(() => { // 清除表单验证结果
        this.$refs.form.clearValidate()
      })

      if (this.currentInfo.isAdd) {
        this.form.val = {}
      } else {
        this.getInfo(val)
      }
    },
    // 获取详情
    getInfo (id) {
      this.spinning = true
      getGroupInfo({ id: id }).then(res => {
        const { id, name, des } = res.content || {}
        this.form.val = { id, name, des }
      }).finally(res => {
        this.spinning = false
      })
    },
    // 关闭弹出框
    closeDetail (val) {
      this.form.confirmLoading = false
      this.$emit('emitToParent', val)
    },
    // 提交表单信息
    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.form.confirmLoading = true
          const params = {
            ...this.form.val,
            courseId: this.currentInfo.courseId
          }
          const fetchFun = this.currentInfo.isAdd ? createGroupInfo : updateGroupInfo
          this.updateInfo(fetchFun, params)
        }
      })
    },
    // 修改表单信息接口相应
    updateInfo (fetchFun, params) {
      fetchFun(params).then(response => {
        this.$message.success((params.id ? '修改' : '新增') + '成功！')
        this.closeDetail(true)
      }).finally(() => {
        this.form.confirmLoading = false
      })
    }
  }
}
</script>
